﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services.Protocols;
using System.Web.UI;
using System.Web.UI.WebControls;
using MedicWeb.MedicService;

namespace MedicWeb.forms.Editors {
    public partial class UserEdit : SessionPage {
        private PublicUser user;

        protected void Page_Load(object sender, EventArgs e) {
            string id = Request.QueryString["id"];
            Form.Action = ResolveUrl("~/forms/Editors/UserEdit.aspx");
            var ms = new MainService();
            if (id != null) {
                Form.Action += "?id=" + id;
                user = ms.LoadUser(GetSession(), int.Parse(id));
            } else {
                user = new PublicUser();
            }
            if (!IsPostBack) {
                tfLogin.Text = user.Login;
                comboRole.SelectedValue = user.Role;
            }

        }

        protected void btnSave_Click(object sender, EventArgs e) {
            try {
                var ms = new MainService();
                user.Login = tfLogin.Text;
                string pass = pfPassword.Text;
                string passConf = pfPasswordConfirm.Text;
                if (pass == passConf && !string.IsNullOrEmpty(pass)) {
                    user.Password = Md5(pfPassword.Text);
                }
                user.Role = comboRole.SelectedValue;
                ms.SaveUser(GetSession(), user);

                Session["success"] = "Изменения сохранены успешно";
            } catch (Exception ex) {

                if (ex.InnerException is SoapException
                    && ((SoapException)ex.InnerException).Detail.InnerText == "AuthorizationException") {
                    throw ex;
                } else {
                    Session["error"] = "Ошибка сохранения";
                }
            }
        }

        public static string Md5(string input) {
            var x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = System.Text.Encoding.UTF8.GetBytes(input);
            bs = x.ComputeHash(bs);
            var s = new System.Text.StringBuilder();
            foreach (byte b in bs) {
                s.Append(b.ToString("x2").ToLower());
            }
            string result = s.ToString();
            return result;
        }
    }
}